<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Loader;
use PHPExcel_IOFactory;
use PHPExcel_Cell;
use PHPExcel;
vendor("PHPExcel.PHPExcel.PHPExcel");
vendor("PHPExcel.PHPExcel.Writer.IWriter");
vendor("PHPExcel.PHPExcel.Writer.Abstract");
vendor("PHPExcel.PHPExcel.Writer.Excel5");
vendor("PHPExcel.PHPExcel.Writer.Excel2007");
vendor("PHPExcel.PHPExcel.IOFactory");
/*
导入
 */
class Salary extends AdminBase{

    public function index(){
        return $this->fetch('index');
    }
    public function indexUser(){
        $time = input('time');
        session('searchTime',$time);
        return $this->fetch('indexuser');
    }
    public function getLists()
    {
        if($this->request->isAjax()) {
            $m = new \app\admin\model\Salary();
            return $m->getLists();
        }
    }
    public function getListsUser()
    {
        if($this->request->isAjax()) {
            $m = new \app\admin\model\Salary();
            return $m->getListsUser();
        }
    }
    public function add(){
        return $this->fetch();
    }
    public function edit($id){
        session('redirect_url',$_SERVER['HTTP_REFERER']);   //记住编辑前的url，修改后调回
        $rows = db('salary')->find($id);
        return $this->fetch('edit',['rows'=>$rows]);
    }
    public function save()
    {
        if($this->request->isAjax()){
            $m = new \app\admin\model\Salary();
            return $m->_save();
        }
    }
    public function update(){
        if($this->request->isPost()){
            $data = $this->request->except('','post');
            //保存数据
            if(db('payroll')->update($data) !== false){
                $this->success('更新成功','index');
            }else{
                $this->error('更新失败');
            }
        }
    }
    // public function delete($id = 0, $ids = [])
    // {
		
        // $id = $ids ? $ids : $id;
        // if ($id) {
			// $m = new \app\admin\model\Salary();
            // if ($m->delete($id)) {
                // $this->success('删除成功');
            // } else {
                // $this->error('删除失败');
            // }
        // } else {
            // $this->error('请选择需要删除的项目');
        // }
    // }
	    //软删除
    public function delete($id = 0, $ids = [])
    {
        if($this->request->isAjax()){
            $id = $ids ? $ids : $id;
			$m = new \app\admin\model\Salary();
            return $m->_delete($id);
        }
    }
    //导入Excel
    public function upload()
    {
        $file = request()->file('file');
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'excel');//上传位置
            $path = ROOT_PATH . 'public' . DS . 'excel' . DS;
            $savePath = $path . $info->getSaveName();//上传后的EXCEL路径
            $res = $this->excelRead($savePath);//传参,判断office2007还是office2003
            /*对生成的数组进行数据库的写入*/

            $succer = 0;
            $data = [];
            $arrUserid = [];
            foreach ($res as $k => $value) {
                if ($k > 1) {
                    if (!$value[0] || !$value[1]|| !$value[2]|| !$value[3]){
                        continue;
                    }
                    $arrUserid[] = trim($value[0]);
                    $data[] = [
                        'userid'=>trim($value[0]),
                        'department'=>trim($value[1]),
                        'name'=>trim($value[2]),
                        'time'=>trim($value[3]),
                        'jbgz'=>trim($value[4]),
                        'gl'=>trim($value[5]),
                        'jb'=>trim($value[6]),
                        'zyb'=>trim($value[7]),
                        'bm'=>trim($value[8]),
                        'zl'=>trim($value[9]),
                        'gwf'=>trim($value[10]),
                        'bt'=>trim($value[11]),
                        'jn'=>trim($value[12]),
                        'tx'=>trim($value[13]),
                        'ct'=>trim($value[14]),
                        'bc'=>trim($value[15]),
                        'zwbt'=>trim($value[16]),
                        'sjjt'=>trim($value[17]),
                        'qt1'=>trim($value[18]),
                        'gwgz'=>trim($value[19]),
                        'ws'=>trim($value[20]),
                        'jrf'=>trim($value[21]),
                        'ds'=>trim($value[22]),
                        'yy'=>trim($value[23]),
                        'bt2'=>trim($value[24]),
                        'zf'=>trim($value[25]),
                        'khgz'=>trim($value[26]),
                        'yfgz'=>trim($value[27]),
                        'bj'=>trim($value[28]),
                        'sj'=>trim($value[29]),
                        'kg'=>trim($value[30]),
                        'k1'=>trim($value[31]),
                        'kqxj'=>trim($value[32]),
                        'znjy'=>trim($value[33]),
                        'jxjy'=>trim($value[34]),
                        'zfdklx'=>trim($value[35]),
                        'zfzj'=>trim($value[36]),
                        'sylr'=>trim($value[37]),
                        'sb'=>trim($value[38]),
                        'zfgjj'=>trim($value[39]),
						'dg'=>trim($value[40]),
                        'djxj'=>trim($value[41]),
                        'gh'=>trim($value[42]),
                        'gts'=>trim($value[43]),
                        'sfje'=>$value[44]
                        ];
                    $succer = $succer + 1;
                }
            }
            session('salaryData',$data);
            session('arrUserid',$arrUserid);
            $this->success('成功导入'.$succer.'条数据','admin/salary/showList');
        }else{
            $this->error('导入失败');
        }

    }

    public function showList()
    {
        return $this->fetch('showlist');
    }

    public function getSalaryLists()
    {
        return session('salaryData');
    }
	public function showListFalse()
    {
        return $this->fetch('showlistfalse');
    }
    public function saveSalary()
    {
        if (session('salaryData') && session('arrUserid')){
            $data = session('salaryData');
            $arrUserid = session('arrUserid');
            $res = db('salary')->insertAll($data);
            if ($res){
                $res1 = send_message_templete1($arrUserid, '薪资发放通知', '您的薪资已发放，请前往工资条应用模块进行查看。', gzt_site_url);
                if ($res1['invaliduser']){
                    $users = explode('|',$res1['invaliduser']);
                    $m = new \app\admin\model\SalaryUser();
                    $userIds = $m->field('id,name,tel')->select();
                    $userFalse = [];
                    foreach ($userIds as $value) {
                        if (in_array(strtolower($value['id']),$users)){
                            $userFalse[] = $value;
                        }
                    }
                    session('salaryDataFalse',$userFalse);
                    $this->success('部分通知消息已发送,未发送成功人员名单','admin/salary/showListFalse');
                }
            }
            $this->success('通知消息已发送','admin/salary/index');
        }else{
            $this->error('已超时','admin/salary/index');
        }

    }
    public function excelRead($filename,$encode='utf-8'){

        Vendor("Excel.PHPExcel.Reader.Excel2007");
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($filename);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getFormattedValue();
            }
        }
        return $excelData;
    }
    public function downloads(){
        $header[]=array(
            "微信ID(微信识别ID)",
            "部门",
            "姓名",
            "月份(不能为空，格式为 201909 ，每人每月录入一次，录入错误进入后台修改)",
            "基本工资（所有金钱数额为数字 200或200.00）",
            "工龄",
            "加班",
            "中夜班",
            "保密",
            "资历",
            "高温费",
            "补贴",
            "技能",
            "通讯",
            "车贴",
            "补差",
            "职务补贴",
            "司机津贴",
            "其它1",
            "岗位工资",
            "卫生",
            "节日费",
            "独生",
            "营养",
            "补贴2",
            "住房",
            "考核工资",
            "应发工资",
            "病假",
            "事假",
            "旷工",
            "扣1",
            "考勤小计",
            "子女教育",
            "继续教育",
            "住房贷款利息",
            "住房租金",
            "赡养老人",
            "社保",
            "住房公积金",
			"待工",
            "代缴小计",
            "工会",
            "个调税",
            "实发金额"
        );
//        $m= new \app\admin\model\SalaryUser();
//        $data = $m->select();
        $d_list = file_get_contents('./gzt_user_list.json');
        $d_list = json_decode($d_list,true);
        foreach ($d_list as $k=> $v){
            if(!is_numeric($v['id'])||strpos($v['id'],".")!==false){
                $data[] = $d_list[$k];
            }
        }
        foreach ($data as $key=> $va){
            $list[$key]['id'] = $va['id'];
            $list[$key]['depart_name'] = $va['depart_name'];
            $list[$key]['name'] = filterEmoji($va['name']);
        }
//        halt($list);
        $data = array_merge_recursive($header,$list);
//        halt($data);
        // array_unshift($header,$list);
        //      $data = array(
        //  array(NULL, 2010, 2011, 2012),
        //  array('Q1',   12,   15,   21),
        //  array('Q2',   56,   73,   86),
        //  array('Q3',   52,   61,   69),
        //  array('Q4',   30,   32,    0),
        // );
        create_xls($data,'salary.xlsx');
    }


//    public function batchDelete(){
//        $yf = input('post.ym');
//        if (!empty($yf)) {
//            $delres = Db::table('hs_payroll')->where('yf',$yf)->delete();
//        }else{
//            $delres = 0;
//        }
//        if ($delres == 0) {
//            $this->flag= '没有可删除的数据';
//        }else{
//            $this->flag="有".$delres."条数据，已被删除";
//        }
//        $this->success($this->flag);
//    }
}

